package per.sunmes.lesrb.layer;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;

import per.sunmes.lesrb.manager.LayerM;
import per.sunmes.lesrb.util.U;

/**
 * 子类可重载initContent方法 ， Layer初始化会调用该方法。<br>
 * 
 * <pre>
 * Layer构造方法已调用 
 * 		U.stageGroup(this); 
 *		setTransform(false);
 * </pre>
 */
public abstract class Layer extends Group implements Disposable {

	protected Array<Dialog> dialogList = new Array<Dialog>();

	public Layer() {
		U.stageSize(this);
		setTransform(false);
	}

	@SuppressWarnings("unchecked")
	public <T extends Dialog> T getDialog(Class<T> cls) {
		for (Dialog dialog : dialogList) {
			if (dialog.getClass() == cls) {
				return (T) dialog;
			}
		}
		return null;
	}

	public void reciveEventMsg(LayerEventMsg msg) {
		childEventMsgHandler(msg);
		for (Dialog dialog : dialogList) {
			dialog.reciveEventMsg(msg);
		}
	};

	protected void childEventMsgHandler(LayerEventMsg msg) {

	}

	protected void addDialog(Dialog dialog) {
		dialog.setParentLayer(this);
		dialogList.add(dialog);
	}

	protected void removeDialog(Dialog dialog) {
		dialog.setParentLayer(null);
		dialogList.removeValue(dialog, true);
	}

	@Override
	public void addActor(Actor actor) {
		super.addActor(actor);
		if (actor instanceof Dialog) {
			addDialog((Dialog) actor);
		}
	}

	@Override
	public boolean removeActor(Actor actor, boolean unfocus) {
		boolean ret = super.removeActor(actor, unfocus);
		if (actor instanceof Dialog) {
			removeDialog((Dialog) actor);
		}
		return ret;
	}

	/** 预载入资源调用 */
	public void preloadResources() {
	}

	/** 载入进度  0 - 1*/
	public float getPreloadPercent() {
		return 1;
	};

	public abstract void initContent();

	/**
	 * 返回是否需要继续处理backCall
	 * 
	 * 子类方法需要添加
	 * 
	 * <pre>
	 * if (!super.backCall()) {
	 * 	return false;
	 * }
	 * </pre>
	 * 
	 * @return
	 */
	public boolean backCall() {
		if (dialogList.size > 0) {
			for (int i = dialogList.size - 1; i >= 0; i--) {
				Dialog dialog = dialogList.get(i);
				if (dialog.isShowed()) {
					if (!dialog.backCall()) {
						return false;
					}
				}
			}
		}
		return childBackCall();
	}

	/**
	 * 子类直接重载这个方法。
	 * 
	 * @return
	 */
	protected boolean childBackCall() {
		return false;
	}

	@Override
	public boolean remove() {
		LayerM.removeDisposeLayer(this);
		return true;
	}

	@Override
	public void dispose() {
		for (Dialog dialog : dialogList) {
			dialog.dispose();
		}

		childDispose();
	};

	public void childDispose() {
	}

}
